package com.aaa.mrcai.service.impl;

import com.aaa.mrcai.mapper.ForgotPsdMapper;
import com.aaa.mrcai.pojo.vo.ForgotPsdVo;
import com.aaa.mrcai.result.AjaxResult;
import com.aaa.mrcai.service.ForgotPsdService;
import com.aaa.mrcai.util.SendCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletContext;


/**
 * Demo class
 *
 * @Author: Wang
 * @Date: Created in 19:41 2021/12/13
 */
@Service
public class ForgotPsdServiceImpl implements ForgotPsdService {

    @Autowired
    private ServletContext servletContext;

    @Autowired
    private ForgotPsdMapper forgotPsdMapper;
    @Override
    public AjaxResult isTelephoneExist(String telephone) {

        long l = forgotPsdMapper.isTelephoneExist(telephone);
        if (l==0){
            return AjaxResult.defeated("手机号不存在 请去注册");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult sendCode(String telephone) {
        int random = (int) (Math.random()*1000000);
        System.out.println(random);
        int i = SendCodeUtil.sendCode(random, telephone);
        if (i>0){
            servletContext.setAttribute(telephone,random);
            return AjaxResult.success("验证码发送成功");
        }
        return AjaxResult.defeated("验证码发送失败");

}

    @Override
    public AjaxResult forgotPsd(ForgotPsdVo forgotPsdVo) {
        long l = forgotPsdMapper.isTelephoneExist(forgotPsdVo.getTelephone());
        if (l==0){
            return AjaxResult.defeated("手机号不存在 请去注册");
        }
        //手机号获取的验证码
        Object o = servletContext.getAttribute(forgotPsdVo.getTelephone());
        System.out.println(o);
        if (o==null){
            return AjaxResult.defeated("请输入验证码");
        }
        if (!o.equals(forgotPsdVo.getCode())){
            return AjaxResult.defeated("验证码错误");
        }else{
//            int psd = forgotPsdMapper.forgotPsd(forgotPsdVo);
            int i = forgotPsdMapper.updatePsd(forgotPsdVo);
            if (i>0){
                return AjaxResult.success("修改密码成功");
            }
            return AjaxResult.defeated("检查过重试");
        }


    }
}
